package com.aos.controller;

import com.aos.client.AuthServiceClient;
import com.aos.dto.UserDto;
import com.aos.entity.User;
import com.aos.properties.APMSProperties;
import com.aos.service.user.UserService;
import com.aos.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @ClassName LoginController
 * @Description:登录控制器
 * @Author wumingwang
 * @Date 2018/9/10 15:45
 * @Version 1.0
 */
@Slf4j
@RestController
@Api(value = "Login Controller", tags = {"登录接口"})
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    AuthServiceClient authServiceClient;

    @Autowired
    private APMSProperties apmsProperties;

    /**
     * 用户登录
     * @param {String} userName 用户名
     * @param {String} password 密码
     * @param {String} appCode 服务标识
     * @return map
     */
    @ApiOperation(value = "用户登录", notes = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名",   required = true,paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "password", value = "密码",   required = true,paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "appCode", value = "服务标识",  required = true,paramType = "query", dataType = "String"),
    })
    @PostMapping("/login/v1/login")
    public Object login(@RequestBody Map<String,String> reqmap){
        String userName = reqmap.get("userName");
        String password = reqmap.get("password");
        String appCode = reqmap.get("appCode");
        if(StringUtils.isEmpty(userName)){
            return Result.error("登录用户名不能为空！");
        }
        if(StringUtils.isEmpty(password)){
            return Result.error("登录密码不能为空！");
        }
        if(StringUtils.isEmpty(appCode)){
            return Result.error("服务标识不能为空！");
        }
        /**用户准入校验*/
        Result result = userService.userLogin(userName,password,appCode);
        if(result.getStatus() != 200){
            return result;
        }
        /**用户准入校验通过后，获取Token*/
        Map<String,Object> map = authServiceClient.getToken(userName,password,apmsProperties.getUser().getLoginType()
                ,appCode,apmsProperties.getApplication().getSecret());
        Result res= userService.operationUser(result,map.get("access_token").toString());
        return res;
    }

    @PostMapping("/login/v1/logout")
    public Object logout(){
        return userService.logout();
    }

}
